use sqlx::{MySqlPool, Row, Error, mysql::MySqlRow};
use crate::{model::user::{User}};

pub struct UserDao<'a> {
    db: &'a MySqlPool
}

impl UserDao<'_> {
    pub fn new(db: &MySqlPool) -> UserDao {
        UserDao {
            db
        }
    }

    pub async fn select_all(&self) -> Vec<User> {
        sqlx::query("select id,account,username from user")
            .map(|row: MySqlRow| User {
                id: row.get("id"),
                username: row.get("username"),
                account: row.get("account"),
                password: None,
                captcha: None
            })
            .fetch_all(self.db).await.unwrap()
    }

    pub async fn select_by_account(&self, account: &String) -> Result<User, Error> {
        let result = sqlx::query("select * from user where account = ?")
            .bind(account)
            .map(|row| User {
                id: row.get("id"),
                username: row.get("username"),
                account: row.get("account"),
                password: row.get("password"),
                captcha: None
            })
            .fetch_one(self.db)
            .await;
        result 
    }
    
    pub async fn account_is_exist(&self, account: &String) -> bool {
        let result = sqlx::query("select account from user where account = ?")
            .bind(account)
            .fetch_one(self.db).await;
        result.is_ok()
    }
    pub async fn add(&self, user: &User) -> bool {
        let result = sqlx::query("insert into user(account, password, username) values(?,?,?)")
            .bind(user.account.clone())
            .bind(user.password.clone().unwrap_or_default())
            .bind(user.username.clone().unwrap_or_default())
            .execute(self.db).await.expect("添加用户失败！");
        result.rows_affected() != 0
    }
}